package com.lanchetech.user.service.impl;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lanchetech.bean.request.PageReq;
import com.lanchetech.bean.response.BasePageResp;
import com.lanchetech.bean.response.BaseResp;
import com.lanchetech.bean.response.ResultData;
import com.lanchetech.bean.util.PageHelpUtil;
import com.lanchetech.bean.vo.VideoVO;
import com.lanchetech.common.enums.ResultCode;
import com.lanchetech.common.enums.VideoAuditStatusEnum;
import com.lanchetech.common.enums.VideoTypeEnum;
import com.lanchetech.dao.SpuMapper;
import com.lanchetech.dao.UserMapper;
import com.lanchetech.dao.VideoGoodsMapper;
import com.lanchetech.dao.VideoMapper;
import com.lanchetech.entity.User;
import com.lanchetech.entity.Video;
import com.lanchetech.entity.VideoGoods;
import com.lanchetech.service.DaoService;
import com.lanchetech.service.OSSClientUtil;
import com.lanchetech.user.service.VideoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class VideoServiceImpl implements VideoService {

    @Autowired
    VideoMapper videoMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    DaoService daoService;

    @Autowired
    VideoGoodsMapper videoGoodsMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    OSSClientUtil ossClientUtil;

    @Autowired
    SpuMapper spuMapper;

    @Override
    public ResultData<VideoVO> getVideoDetail(User user, Long id) {
        videoMapper.addOneViewsById(id);

        VideoVO vo = new VideoVO();
        Video video = videoMapper.selectByPrimaryKey(id);
        BeanUtils.copyProperties(video, vo);
        if(!StringUtils.isEmpty(video.getSpuIds())){
            List<Long> ids = JSON.parseArray(video.getSpuIds(), Long.class);
            if(ids.size() > 0){
                vo.setSpuList(spuMapper.findAllByIds(ids));
            }
        }
        if(user != null){
            VideoGoods videoGoods = videoGoodsMapper.findOneByUserIdAndVideoId(user.getId(), id);
            vo.setHasGood(videoGoods != null);
        }
        return new ResultData<>(vo);
    }

    private String buildImage(Video video){
        if(video.getMainImage() != null){
            return video.getMainImage();
        }else{
            try {
              return ossClientUtil.uploadWebImageOriginally(video.getVideo() + "?x-oss-process=video/snapshot,t_1000,f_png,w_0,h_0,m_fast");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public BaseResp editVideo(Video video) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        if (video.getId() == null) {
            // 新增
            video.setUserId(user.getId());
            video.setGoods(0);
            video.setViews(0);
            video.setType(VideoTypeEnum.DEFAULT.getType());
            video.setStatus(VideoAuditStatusEnum.PENDING.getStatus());
            video.setMainImage(buildImage(video));
            video.setCreatedAt(new Date());
            video.setUpdatedAt(new Date());
            videoMapper.insert(video);
        } else {
            Video result = videoMapper.selectByPrimaryKey(video.getId());
            if(!result.getUserId().equals(user.getId())){
                return new BaseResp(ResultCode.FAIL);
            }
            video.setMainImage(buildImage(video));
            // 每次编辑，都要重新审核
            video.setStatus(VideoAuditStatusEnum.PENDING.getStatus());
            video.setUpdatedAt(new Date());
            videoMapper.updateByPrimaryKeySelective(video);
        }
        return new BaseResp();
    }

    @Override
    public ResultData<BasePageResp<VideoVO>> getVideoPage(User user, PageReq req) {
        req.setStatus(VideoAuditStatusEnum.PASS.getStatus());
        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<VideoVO> list = videoMapper.findAllPage(req);

        if(!CollectionUtils.isEmpty(list)){
            Map<Long, Boolean> goodsMap = new HashMap<>();

            if(user != null){
                List<VideoGoods>  goods = videoGoodsMapper.findAllByUserIdAndVideoIds(user.getId(), list.stream().map(Video::getId).collect(Collectors.toList()));
                goods.stream().forEach(item->goodsMap.put(item.getVideoId(), true));
            }

            list.stream().forEach(item->{
                item.setHasGood(goodsMap.containsKey(item.getId()));
            });
        }

        return PageHelpUtil.buildPage(list, page);
    }

    @Override
    public BaseResp deleteVideo(Long id) {
        videoMapper.deleteByPrimaryKey(id);
        return new BaseResp();
    }

    @Override
    public BaseResp toggleVideoGoods(Long id) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        VideoGoods videoGoods = videoGoodsMapper.findOneByUserIdAndVideoId(user.getId(), id);
        if(videoGoods == null){
            videoGoodsMapper.insert(VideoGoods.builder()
                    .userId(user.getId())
                    .videoId(id)
                    .createdAt(new Date())
                    .build());
            videoMapper.addOneGoodsById(id);
        }else{
            videoGoodsMapper.deleteByPrimaryKey(videoGoods.getId());
            videoMapper.subOneGoodsById(id);
        }

        return new BaseResp();
    }
}